﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web.Mvc;
using System.Web.UI;
using System.Xml.Linq;
using Core.BOL;
using Core.DAL;
using Core.Utils;
using System.Security.Permissions;

namespace ScoutNET.Controllers
{
    public class HomeController : ApplicationController
    {
        private ImagesRepository ir = new ImagesRepository();
        private NewsRepository nr = new NewsRepository();
        private CalendarRepository cr = new CalendarRepository();

        public ActionResult Index()
        {
            ViewData["PageTitle"] = Resources.Home_Index_Title;
            ViewData["PageDescription"] = Resources.Home_Index_Description;

            sp_Site_GetRandomImageResult i = ir.GetRandomImage(1).SingleOrDefault();

            ViewData["News"] = nr.GetNews(0,4);
            ViewData["RandomImg"] = i;

            ViewData["LatestEvents"] = cr.GetNextEvents();

            return View();
        }

        [OutputCache(CacheProfile = "Photo")]
        [EnvironmentPermissionAttribute(SecurityAction.LinkDemand, Unrestricted = true)]
        public ActionResult ImageResize(int? ID, string title)
        {
            if (ID != null)
            {
                byte[] baImage = Imaging.GetResizedImage((int)ID, ImageMode.Home, false);

                return new FileContentResult(baImage, "image/jpeg");
            }
            else
            {
                return View("Error404");
            }
        }

        [OutputCache(Duration = 6000, VaryByParam = "none", Location = OutputCacheLocation.ServerAndClient)]
        public JsonResult FeedReader()
        {
            string key = "HomeFeed";

            if (this.HttpContext.Cache[key] == null)
            {
                XDocument list = XDocument.Load(this.HttpContext.Server.MapPath("~/App_Data/HomeRssFeed.xml"));
            
                var query = (from c in list.Elements("RssFeeds").Elements("RssFeed")
                             select new
                             {
                                 Url = c.Attribute("Url").Value,
                                 Name = c.Attribute("Name").Value
                             }).ToList();

                List<RssItem> lRssItems = new List<RssItem>();
                foreach (var item in query)
                {
                    try
                    {
                        RssFeed rssFeed = RssReader.GetFeed(item.Url, item.Name);
                        lRssItems.AddRange(rssFeed.Items);   
                    }
                    catch(Exception ex)
                    {
                        Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                    }
                }

                var lRSS = (from rss in lRssItems
                            orderby rss.Pubdate descending
                            select new
                            {
                                Title = rss.Title,
                                Pubdate = rss.Pubdate,
                                Source = rss.Source,
                                Link = rss.Link
                            }).Take(12).ToList();

                this.HttpContext.Cache.Insert(key, lRSS, null, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration);
            }

            return this.Json(this.HttpContext.Cache[key], JsonRequestBehavior.AllowGet);
        }
    }

}
